package com.pets.service.Impl;

import com.pets.dao.KnowledgeMapper;
import com.pets.entity.Knowledge;
import com.pets.enums.YesNoEnum;
import com.pets.qo.KnowledgeAddQO;
import com.pets.service.KnowledgeService;
import com.pets.service.UserService;
import com.pets.util.PageData;
import com.pets.util.Result;
import com.pets.util.UploadUtil;
import com.pets.vo.KnowledgesByPageVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class KnowledgeServiceImpl implements KnowledgeService {
    @Autowired
    private KnowledgeMapper knowledgeDao;

    //分页查询
    @Override
    public PageData<KnowledgesByPageVO> selectKnowledgesByPage(int page, int pageSize) {
        PageData<KnowledgesByPageVO> pd = new PageData<>();
        pd.setPage(page);
        pd.setPageSize(pageSize);
        List<KnowledgesByPageVO> knowledgesByPageVOS = knowledgeDao.selectKnowledgesByPage((page-1)*pageSize, pageSize);
        int total = knowledgeDao.selectKnowledgesCount();
        pd.setTotal(total);
        pd.setTotalPage(pd.getTotalPage());
        if (knowledgesByPageVOS.size() > 0) {
            pd.setData(knowledgesByPageVOS);
        }
        return pd;
    }

    //百科知识的添加操作
    public Result KnowledgeAddQO( KnowledgeAddQO knowledgeAddQO){
        Result result=new Result();
        //做文件上传动作
        String url ;
        try {
             url = UploadUtil.uploadFile(knowledgeAddQO.getFile());
        } catch (IOException e) {
            result.setCode(YesNoEnum.NO.getCode());
            result.setMsg("文件上传失败");
            //查看完整错误信息,尽量少用，可能会导致锁死
            e.printStackTrace();
            return result;
        }
        Knowledge knowledge=new Knowledge();
        knowledge.setKtitle(knowledgeAddQO.getkTitle());
        knowledge.setKcontent(knowledgeAddQO.getkContent());
        knowledge.setKpicture(url);
        knowledge.setKstatus(0);
        knowledge.setKtime(new Date());
        knowledge.setUid(knowledgeAddQO.getuId());
        int i=knowledgeDao.insert(knowledge);
        if(i >0){
            result.setCode(YesNoEnum.YES.getCode());
            result.setMsg("百科知识添加成功");
            return result;
        }else {
            result.setCode(YesNoEnum.NO.getCode());
            result.setMsg("百科知识添加失败");
            return result;
        }

    }

    /**
     * 单条百科知识的显示
     * @param kid
     * @return
     */
    public KnowledgesByPageVO show(int kid){
        KnowledgesByPageVO k=knowledgeDao.selectKnowledgeByKid(kid);
        if(k!=null) {
            return k;
        }
        return null;
    }
}
